Imports System
Imports System.Configuration
Imports MyClasses
Imports DAL
Imports System.Text
Imports BAL

Public Class FrmNGSaleReturn

#Region "Declaration"


    Private intTotalColumns As Integer = 26      'Sale Item's no of Columns    
    'Private intCurrentRow As Integer = 0         'Used to store current row no where item insertion/updation is in process  or done
    Private intLastRow As Integer = 0         'Used to store current row no where item insertion/updation is in process  or done

    Private TotAmount As Double               'Used to show Total Amount of Active Items  in Current Counter
    Private btStatus As Byte                  'Current Record Status 
    Private intGrdCntRows As Integer = 31
    'Private intCrntItmCnt As Integer             'Used to show No of Active Items  in Current Counter
    Private BtLoading As Boolean                    'Variable is used to avoid unNecessary loops/events/execution while setting or Loading the Data                     

    Private intParty As Integer = 0           'Variable stores currently selected party 
    Private intPack As Integer = 0
    Private intPromoter As Integer = 0           'Variable stores currently selected promoter
    Private intColor As Integer = 0
    Private IntItem As Integer = 0
    Private intPriceList As Integer = 0
    Private intSite As Integer = 0
    Private intGodownID As Integer = 0
    Private intPackingUpdateID As Integer = 0
    Private saleType As DGeneral.DocTypes
    Private intVoucherID As Integer

#End Region '"DECLARATION"

#Region " Form( & control) Events"
    Private Sub txtAmt_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtTotalAmt.KeyDown, txtGrossAmt.KeyDown, txtOtherCharges.KeyDown
        e.SuppressKeyPress = True  'INSTEAD OF DISABLE CONTROL(IT AFFECTS THE UI) MANUAY KEYS ARE SUPPRESSED SO USER CANT EDIT  THE VALUE. TEXT BOX LOOKS ENABLE BUT NOT
    End Sub

    Private Sub txtReturn_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtGrossAmt.KeyDown
        e.SuppressKeyPress = True 'INSTEAD OF DISABLE CONTROL(IT AFFECTS THE UI) MANUAY KEYS ARE SUPPRESSED SO USER CANT EDIT  THE VALUE. TEXT BOX LOOKS ENABLE BUT NOT
    End Sub

    Private Sub txtPaidAmt_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtOtherCharges.KeyDown
        Try
            If e.KeyCode = Keys.Enter Then
                btnSave.Focus()
            Else
                If e.Alt = True Then Exit Sub
                If BCommon.ValidateText(txtOtherCharges.Text, e.KeyCode, "NUM", False) = False Then
                    e.SuppressKeyPress = True
                ElseIf e.Shift Then
                    e.SuppressKeyPress = True : Exit Sub
                End If
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "txtPaidAmt_KeyDown")
        End Try
    End Sub

    Private Sub txtPaidAmt_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtOtherCharges.KeyUp
        Try
            If e.KeyCode = Keys.Enter Then
                If txtOtherCharges.Text >= txtTotalAmt.Text Then
                    txtGrossAmt.Text = Format((txtOtherCharges.Text - txtTotalAmt.Text), "##,##0.00")
                Else : txtGrossAmt.Text = "0.00"  'NOW THIS FORM IS FOR COUNTER SALE ONLY SO THERE IS NO VALIDATION LIKE THIS 'CHANDRAKANT
                End If
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "txtPaidAmt_KeyUp")
        End Try
    End Sub

    Private Sub frmSale_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try
            'If DSale.GetCounterDetails().Rows.Count > 0 Then
            '    'Select Case MessageBox.Show(BCommon.GetMessage(10327), BCommon.GetConfigValues("MsgTitle"), MessageBoxButtons.YesNoCancel)
            '    Select Case BCommon.ShowMsgError(10327, "YNC")
            '        Case Windows.Forms.DialogResult.Yes      'SAVE All COUNTER DATA & CLOSE.
            '            'save data
            '            BCommon.ShowMsgError(3)
            '        Case Windows.Forms.DialogResult.No       'CLOSE THE FORM
            '            'NO NEED TO CODE
            '        Case Windows.Forms.DialogResult.Cancel   'CANCEL THE FORM CLOSE EVENT
            '            e.Cancel = True
            '    End Select
            'End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "frmSale_FormClosing")
        End Try
    End Sub

    Private Sub frmSale_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            BtLoading = True
            BCommon.SetFormStandards(Me)

            Call DisplayData()
            txtPartyCode.Focus()
            BtLoading = False
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "frmSale_Load")
        End Try
    End Sub

    'Private Sub txtPaidAmt_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtOtherCharges.LostFocus
    '    Call CalculateReturnAmt()
    'End Sub

#End Region

#Region "GRID SETTINGS"

    Private Sub SetGrids()
        Try
            'ITEM DISPLAY GRID
            With fgItems
                .Left = pnlMain.Left + 5
                .Width = pnlMain.Width - 1
                .RowHeadersVisible = False
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .AllowUserToOrderColumns = False
                .AllowUserToResizeRows = False
                .AllowUserToResizeColumns = False

                '.AllowDelete = True
                .RowCount = 30
                '.Cols.Fixed = 0
                .ColumnCount = intTotalColumns
                .ScrollBars = ScrollBars.None
                '.AllowAddNew = False
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect


                Call SetGridCaptions()

                'HIDDEN COLUMNS
                For intcnt As Integer = 0 To .ColumnCount - 1

                    .Columns(intcnt).Visible = False
                    .Columns(intcnt).ReadOnly = True
                    '  .Width = 0
                Next
                .Columns(ItemGridColumns.CODE).Visible = True
                .Columns(ItemGridColumns.ITEMNAME).Visible = True
                .Columns(ItemGridColumns.CLRCODE).Visible = True
                .Columns(ItemGridColumns.CLRDESC).Visible = True
                .Columns(ItemGridColumns.PACK).Visible = True
                .Columns(ItemGridColumns.GODOWN).Visible = True
                ' .Columns(ItemGridColumns.DISC).Visible = True
                .Columns(ItemGridColumns.QTY).Visible = True
                .Columns(ItemGridColumns.PRICE).Visible = True
                .Columns(ItemGridColumns.AMOUNT).Visible = True

            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SetGrids")
        End Try
    End Sub

    Private Sub SetColumnWidths()
        Dim intColWidth As Integer = fgItems.Width / (10 * 3) '10 number of visible columns *3
        Try
            With fgItems

                .Columns(ItemGridColumns.CODE).Width = intColWidth * 3
                .Columns(ItemGridColumns.ITEMNAME).Width = intColWidth * 7
                .Columns(ItemGridColumns.CLRCODE).Width = intColWidth * 2
                .Columns(ItemGridColumns.CLRDESC).Width = intColWidth * 3
                .Columns(ItemGridColumns.PACK).Width = intColWidth * 3
                .Columns(ItemGridColumns.GODOWN).Width = intColWidth * 3
                .Columns(ItemGridColumns.QTY).Width = intColWidth * 2
                '.Columns(ItemGridColumns.DISC).Width = intColWidth * 2
                .Columns(ItemGridColumns.PRICE).Width = intColWidth * 2
                .Columns(ItemGridColumns.AMOUNT).Width = intColWidth * 3


                txtItemCode.Width = .Columns(ItemGridColumns.CODE).Width
                txtItemName.Width = .Columns(ItemGridColumns.ITEMNAME).Width
                txtCLRCODE.Width = .Columns(ItemGridColumns.CLRCODE).Width
                txtCLRNAME.Width = .Columns(ItemGridColumns.CLRDESC).Width
                cmbPack.Width = .Columns(ItemGridColumns.PACK).Width
                txtGoDown.Width = .Columns(ItemGridColumns.GODOWN).Width
                txtQty.Width = .Columns(ItemGridColumns.QTY).Width
                'txtDisc.Width = .Columns(ItemGridColumns.DISC).Width
                txtPrice.Width = .Columns(ItemGridColumns.PRICE).Width
                txtItemAmount.Width = .Columns(ItemGridColumns.AMOUNT).Width


                txtItemCode.Left = .Left
                txtItemName.Left = txtItemCode.Left + txtItemCode.Width
                txtCLRCODE.Left = txtItemName.Left + txtItemName.Width
                txtCLRNAME.Left = txtCLRCODE.Left + txtCLRCODE.Width
                cmbPack.Left = txtCLRNAME.Left + txtCLRNAME.Width
                txtGoDown.Left = cmbPack.Left + cmbPack.Width

                ' txtDisc.Left = txtGoDown.Left + txtGoDown.Width
                txtQty.Left = txtGoDown.Left + txtGoDown.Width
                txtPrice.Left = txtQty.Left + txtQty.Width
                txtItemAmount.Left = txtPrice.Left + txtPrice.Width

                .Columns("ITEMID").Width = 0                       'Hidden Column         
                .Columns("SCHEMEID").Width = 0                    'Hidden Column   
                .Columns("STATUS").Width = 0                    'Hidden Column     
                .Columns("PURCHASEPRICE").Width = 0             'Hidden Column
                .Columns("SEQID").Width = 0                     'Hidden Column       
                .Columns("COLORID").Width = 0                  'Hidden Column     
                .Columns("CONVERSIONUNIT").Width = 0            'Hidden Column
                .Columns("SCHEDULEDRUG").Width = 0              'Hidden Column  
                .Columns("EMERGENCYSTOCK").Width = 0            'Hidden Column 
                .Columns("TOTALSTOCK").Width = 0                'Hidden Column     
                .Columns("STOCKDETAILS").Width = 0              'Hidden Column   
                .Columns("SCHEMESTOCK").Width = 0               'Hidden Column   
                .Columns("TAX").Width = 0                       'Hidden Column   

            End With

        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SetColumnWidths")
        End Try
    End Sub

    Private Sub SetGridCaptions()
        Try
            With fgItems
                'SET COLUMN NAMES
                .Columns(0).Name = "ITEMID"
                .Columns(1).Name = "CODE"
                .Columns(2).Name = "ITEMNAME"
                .Columns(3).Name = "CLRCODE"
                .Columns(4).Name = "CLRDESC"
                .Columns(5).Name = "PACK"
                .Columns(6).Name = "GODOWN"
                .Columns(7).Name = "SCHEMEID"
                .Columns(8).Name = "SCHEME"
                .Columns(9).Name = "QTY"
                .Columns(10).Name = "RATE"
                .Columns(11).Name = "AMOUNT"
                .Columns(12).Name = "STATUS"
                .Columns(13).Name = "EXPIRY"
                .Columns(14).Name = "PURCHASEPRICE"
                .Columns(15).Name = "SEQID"
                .Columns(16).Name = "COLORID"
                .Columns(17).Name = "CONVERSIONUNIT"
                .Columns(18).Name = "SCHEDULEDRUG"
                .Columns(19).Name = "EMERGENCYSTOCK"
                .Columns(20).Name = "TOTALSTOCK"
                .Columns(21).Name = "STOCKDETAILS"
                .Columns(22).Name = "ISMULTIBATCH"
                .Columns(23).Name = "SCHEMESTOCK"
                .Columns(24).Name = "COLORID"
                .Columns(25).Name = "TAX"

                'SET COLUMN CAPTIONS
                .Columns("ITEMID").HeaderText = "ITEMID"
                .Columns("CODE").HeaderText = "CODE"
                .Columns("ITEMNAME").HeaderText = "ITEMNAME"
                .Columns("CLRCODE").HeaderText = "COLOR CODE"
                .Columns("CLRDESC").HeaderText = "COLOR DESC"
                .Columns("GODOWN").HeaderText = "GODOWN"
                .Columns("SCHEMEID").HeaderText = "SCHEMEID"
                .Columns("SCHEME").HeaderText = "SCHEME"
                .Columns("PACK").HeaderText = "PACK"
                .Columns(ItemGridColumns.QTY).HeaderText = "QTY"
                .Columns("RATE").HeaderText = "PRICE"
                .Columns("AMOUNT").HeaderText = "AMOUNT"
                .Columns("STATUS").HeaderText = "STATUS"
                .Columns("EXPIRY").HeaderText = "EXPIRY"
                .Columns("PURCHASEPRICE").HeaderText = "PURCHASE PRICE"
                .Columns("SEQID").HeaderText = "SEQ ID"
                .Columns("COLORID").HeaderText = "COLORID"
                .Columns("CONVERSIONUNIT").HeaderText = "CONVERSION UNIT"
                .Columns("SCHEDULEDRUG").HeaderText = "SCHEDULEDRUG"
                .Columns("EMERGENCYSTOCK").HeaderText = "EMERGENCYSTOCK"
                .Columns("TOTALSTOCK").HeaderText = "TOTALSTOCK"
                .Columns("STOCKDETAILS").HeaderText = "STOCKDETAILS"
                .Columns("ISMULTIBATCH").HeaderText = "ISMULTIBATCH"
                .Columns("SCHEMESTOCK").HeaderText = "SCHEMESTOCK"
                .Columns("TAX").HeaderText = "TAX APPLIED"
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SetGridCaption")
        End Try
    End Sub

#End Region '"GRID SETTINGS"

#Region "GRID EVENT FUNCTIONS"
#End Region '"GRID EVENT FUNCTIONS"

#Region "BUTTON EVENTS"
    Private Sub BtnCash_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnCash.Click
        Try
            Me.BtnCash.BackColor = Color.SteelBlue
            Me.BtnChallan.BackColor = Color.WhiteSmoke
            Me.BtnInvoice.BackColor = Color.WhiteSmoke
            Me.BtnApprove.BackColor = Color.WhiteSmoke
            Me.BtnQuote.BackColor = Color.WhiteSmoke
            saleType = DGeneral.DocTypes.CASH_MEMO
            SubPriSetSeqID()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "Button1_Click")
        End Try
    End Sub

    Private Sub BtnChallan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnChallan.Click
        Try
            Me.BtnCash.BackColor = Color.WhiteSmoke
            Me.BtnChallan.BackColor = Color.SteelBlue
            Me.BtnInvoice.BackColor = Color.WhiteSmoke
            Me.BtnApprove.BackColor = Color.WhiteSmoke
            Me.BtnQuote.BackColor = Color.WhiteSmoke
            saleType = DGeneral.DocTypes.CHALLAN
            SubPriSetSeqID()

        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "BtnChallan_Click")
        End Try
    End Sub

    Private Sub BtnInvoice_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnInvoice.Click
        Try
            Me.BtnCash.BackColor = Color.WhiteSmoke
            Me.BtnChallan.BackColor = Color.WhiteSmoke
            Me.BtnInvoice.BackColor = Color.SteelBlue
            Me.BtnApprove.BackColor = Color.WhiteSmoke
            Me.BtnQuote.BackColor = Color.WhiteSmoke
            saleType = DGeneral.DocTypes.INVOICE
            SubPriSetSeqID()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "BtnInvoice_Click")
        End Try
    End Sub

    Private Sub BtnApprove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnApprove.Click
        Try
            Me.BtnCash.BackColor = Color.WhiteSmoke
            Me.BtnChallan.BackColor = Color.WhiteSmoke
            Me.BtnInvoice.BackColor = Color.WhiteSmoke
            Me.BtnApprove.BackColor = Color.SteelBlue
            Me.BtnQuote.BackColor = Color.WhiteSmoke
            saleType = DGeneral.DocTypes.APPROVAL
            SubPriSetSeqID()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "BtnApprove_Click")
        End Try
    End Sub

    Private Sub BtnQuote_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnQuote.Click
        Try
            Me.BtnCash.BackColor = Color.WhiteSmoke
            Me.BtnChallan.BackColor = Color.WhiteSmoke
            Me.BtnInvoice.BackColor = Color.WhiteSmoke
            Me.BtnApprove.BackColor = Color.WhiteSmoke
            Me.BtnQuote.BackColor = Color.SteelBlue
            saleType = DGeneral.DocTypes.QUOTATION
            SubPriSetSeqID()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "Button5_Click")
        End Try
    End Sub
    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Try
            ' If btStatus = 1 Then 'Current Record is Updated 
            Me.Close()   'Current Record is not updated
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "btnClose_Click")
        End Try
    End Sub

    'Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
    '    Try
    '        If ItemsSelected("A") = True Then
    '            SaveBill()
    '        Else : BCommon.ShowMsgError(10326)                'Modified By:-(2008/01/05) 'FOR BLANK GRID VALIDATION ON PRINT BUTTON
    '        End If
    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "BtnPrint_Click")
    '    End Try
    'End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Try
            '    If btStatus = 1 Then SaveCurrentItem(intCurrentRow)
            If ValidateInfo() = True Then
                If SaveData() = 1 Then
                    BCommon.ShowMsgError(3)
                    Call ClearData()
                    '     GetCounterData()
                    Select Case saleType
                        Case DGeneral.DocTypes.CHALLAN
                            Call BtnChallan_Click(Nothing, Nothing)
                        Case DGeneral.DocTypes.CASH_MEMO
                            Call BtnCash_Click(Nothing, Nothing)
                        Case DGeneral.DocTypes.APPROVAL
                            Call BtnApprove_Click(Nothing, Nothing)
                        Case DGeneral.DocTypes.INVOICE
                            Call BtnInvoice_Click(Nothing, Nothing)
                        Case DGeneral.DocTypes.QUOTATION
                            Call BtnQuote_Click(Nothing, Nothing)
                    End Select
                End If
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "btnSaveCounter_Click")
        End Try
    End Sub
    Private Sub SubPriSetSeqID()
        txtVoucher.Text = BCommon.GetSequentialID(saleType)
    End Sub
#End Region  '"BUTTON EVENTS"


    Private Sub DisplayData()
        Try
            BtLoading = True
            'saleType = DocTypes.CASH_MEMO
            FillPriceListCombo()


            intLastRow = 0
            dtpSaleDate.Value = Now.Date
            dtpSaleDate.Enabled = False
            lblCurrancy1.Text = BCommon.GetConfigValues("Currency")
            lblCurrancy2.Text = lblCurrancy1.Text
            lblCurrancy3.Text = lblCurrancy1.Text
            BtnCash_Click(Nothing, Nothing)
            SubPriSetSeqID()

            Call SetGrids()
            Call SetOtherCharges()
            Call SetColumnWidths()
            Call SetTabIndexes()



            'pnlShortCuts.Location = fgItems.Location
            'pnlShortCuts.Size = fgItems.Size


            BtLoading = False

            BCommon.SetTextReadOnly(txtVoucher)
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "DisplayData")
        End Try
    End Sub

    Private Sub ClearData()
        Try

            BtLoading = True
            intLastRow = 0
            btStatus = 0

            intVoucherID = 0
            txtGrossAmt.Text = "0.00"
            txtTotalAmt.Text = "0.00"
            txtOtherCharges.Text = "0.00"

            subPriClearItemDtls()
            SetOtherCharges()

            intPromoter = 0
            intParty = 0
            intSite = 0
            intPriceList = 0

            txtPartyCode.Text = String.Empty
            txtPartyName.Text = String.Empty
            txtPromoterCode.Text = String.Empty
            txtPromoterName.Text = String.Empty
            txtSiteCode.Text = String.Empty
            txtSiteName.Text = String.Empty
            rTxtAddress.Text = String.Empty
            CmbPriceList.SelectedIndex = 0
            TotAmount = 0.0

            With fgItems
                .Rows.Clear()
                .Rows.Add(20)
                .Refresh()
            End With
            BtLoading = False
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "ClearData")
        End Try
    End Sub

    'Private Function SaveBill() As Integer
    '    'A:- Save All Items on Current Counter
    '    'S:- Save Selected Items on Current Counter
    '    'Saves Selected Items to Test Files & Calls SalePrintForm
    '    Try
    '        'If Not IsNothing(fgItems.Item(fgItems.Row, "STATUS")) AndAlso (Trim(fgItems.Item(fgItems.Row, "STATUS")) = "A" OrElse Trim(fgItems.Item(fgItems.Row, "STATUS")) = "U") Then
    '        '    SaveCurrentItem(fgItems.Row)
    '        'End If

    '        If ValidateAmt() = True Then

    '            Dim printSale As New frmSalePrint
    '            With printSale
    '                .StartPosition = FormStartPosition.Manual
    '                Dim pt As New Point
    '                .Size = Me.Size
    '                .intCounter = 0
    '                pt.Y = ((MDIPharmacy.MdiScaleHeight - .Height) / 2) + MDIPharmacy.pnlHeading.Height + MDIPharmacy.MenuStrip.Height
    '                pt.X = (MDIPharmacy.MdiScaleWidth - .Width) / 2
    '                .ParentTop = Me.Parent.Top
    '                .Location = pt
    '                ' .ItemsFromSale = fgItems.Rows.Selected
    '                '.frmListProducts = Me.frmListProducts


    '                .ShowDialog(MDIPharmacy)
    '                .Dispose()
    '                'SetProductListFormSize()
    '                'If .IsBillSaved = 1 Then  'ITEMS ARE SAVED FROM PRINTS SALE FORM
    '                BtLoading = TRUE
    '                fgItems.Refresh()
    '                BtLoading = FALSE

    '                Call CalculateAmt()
    '            End With
    '        End If
    '        Return 1
    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SaveBill")
    '        Return 0
    '    Finally
    '    End Try
    'End Function

    Private Function SaveData() As Byte
        'Try
        '    Dim objsale As CSale = SetSaleData()
        '    Dim objsaleItem() As cSaleItem = SetSaleItemDetails()
        '    Dim objdSale As DSale = New DSale()
        '    If objdSale.Save(objsale, objsaleItem, dgOtherCharges.DataSource,dg intVoucherID) > 0 Then
        '        Return 1
        '    Else : Return 0
        '    End If
        'Catch ex As Exception
        '    BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SaveData")
        '    Return 0
        'End Try
    End Function

    Private Sub SetItemAmount(ByVal intRow As Integer)
        Try

            With fgItems
                Dim FinalAmount As Double = CDbl(.Item(ItemGridColumns.QTY, intRow).Value) * CDbl(.Item(ItemGridColumns.PRICE, intRow).Value)

                .Item(ItemGridColumns.AMOUNT, intRow).Value = Math.Round(FinalAmount, 2)
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SetItemAmount")
        End Try
    End Sub


    Private Function SetSaleData() As CSale
        Dim objsale As New CSale
        'Dim intCount As Integer
        Dim TotAmount As Double
        'Dim TotDisc As Double
        Try
            With objsale
                ' .PartyID = CustID
                .SaleDate = Me.dtpSaleDate.Value
                .IsFinalBill = True
                'For intCount = 1 To fgItems.Rows.Count
                '    If Not IsNothing(fgItems.Columns("ITEMID").Item(intCount)) Then
                '        TotAmount = TotAmount + fgItems.Columns("AMOUNT").Item(intCount)
                '    Else : Exit For
                '    End If
                'Next
                .SaleBillID = intVoucherID
                .SaleType = saleType
                TotAmount = System.Convert.ToDouble(txtTotalAmt.Text.Trim())
                .Amount = TotAmount
                .dblOtherCharges = System.Convert.ToDouble(txtOtherCharges.Text.Trim())
                .Discount = 0
                .TotalTax = 0

                .GrossAmt = System.Convert.ToDouble(txtGrossAmt.Text.Trim())
                .PartyID = intParty 'cmbPartyCode.SelectedValue
                .PromoterID = intPromoter 'CmbPromoterCode.SelectedValue
                .Site = intSite
                .priceListID = intPriceList
                .ShippingAdress = rTxtAddress.Text.Trim()
            End With
            Return objsale
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SetSaleData")
            Return Nothing
        End Try
    End Function

    Private Function SetSaleItemDetails() As cSaleItem()
        Dim objsaleItem() As cSaleItem
        Dim intCount As Integer
        Dim intRowCount As Integer = 0
        Try
            For intCount = 0 To fgItems.Rows.Count - 1

                If fgItems.Item(ItemGridColumns.ITEMID, intCount).Value = Nothing OrElse Trim(fgItems.Item(ItemGridColumns.ITEMID, intCount).Value.ToString) = "" Then
                    Exit For
                Else
                    ReDim objsaleItem(intRowCount - 1)
                    ' objsaleItem(intRowCount - 1) =
                    intRowCount = intRowCount + 1
                End If
            Next
            ReDim objsaleItem(intRowCount - 1)
            For intCount = 0 To intRowCount - 1
                objsaleItem(intCount) = New cSaleItem
                objsaleItem(intCount) = SetSaleItemDetail(intCount)
            Next
            Return objsaleItem
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SetSaleItemDetails")
            Return Nothing
        End Try
    End Function

    Private Function SetSaleItemDetail(ByVal intRow As Integer) As cSaleItem
        Dim Item As cSaleItem = New cSaleItem
        Try
            With Item
                .PACK = fgItems.Item(ItemGridColumns.PACKID, intRow).Value
                .ColorCode = fgItems.Item(ItemGridColumns.CLRID, intRow).Value
                .ItemID = fgItems.Item(ItemGridColumns.ITEMID, intRow).Value
                .Quantity = fgItems.Item(ItemGridColumns.QTY, intRow).Value
                .Amount = fgItems.Item(ItemGridColumns.AMOUNT, intRow).Value
                .SaleRate = fgItems.Item(ItemGridColumns.PRICE, intRow).Value
                .intPackUpdateID = fgItems.Item(ItemGridColumns.PACKUPDATEID, intRow).Value
                '.Status = chrSaveOrUpdate
                '.PACK = fgItems.Item(ItemGridColumns.PACK, intRow).Value
            End With

            Return Item
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SetSaleItemDetail")
            Return Nothing
        End Try
    End Function


    Private Function ValidateInfo() As Boolean
        '
        Try

            Return True
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "ValidateInfo")
        End Try
    End Function



    'Private Sub DisplayShortCuts(ByVal ShowOrHide As Char)
    '    Try
    '        If ShowOrHide = "S" Then  'SHOW SHORTCUTS
    '            pnlShortCuts.BringToFront()
    '            pnlShortCuts.Visible = True
    '            pnlAmount.Enabled = False
    '            fgItems.Visible = False

    '        ElseIf ShowOrHide = "H" Then 'SHOW REGULAR SALE 'HIDE OTHERS
    '            fgItems.Visible = True
    '            fgItems.BringToFront()
    '            pnlShortCuts.Visible = False
    '            pnlAmount.Enabled = True

    '        End If
    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "DisplayShortCuts")
    '    End Try
    'End Sub

    'Private Function SaveCurrentItem(ByVal intCurrentItemRow As Integer) As Byte
    '    Try

    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SaveCurrentItem")
    '    End Try
    'End Function



    Private Sub FillPriceListCombo()


        Dim dtbPriceList As DataTable = DSale.GetPriceList()
        CmbPriceList.DataSource = dtbPriceList
        CmbPriceList.DisplayMember = "PRICELISTNAME"
        CmbPriceList.ValueMember = "ID"
        intPriceList = CmbPriceList.SelectedValue
    End Sub

#Region "ONLY FOR SALE FORM"
    Private Sub SetTabIndexes()
        Try
            lblPaidAmt.TabIndex = fgItems.TabIndex + 1
            txtOtherCharges.TabIndex = lblPaidAmt.TabIndex + 1
            pnlAmount.TabIndex = txtOtherCharges.TabIndex + 1
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "SetTabIndexes")
        End Try
    End Sub

    'Private Function SetSaleBill(ByVal CounterNo As Integer) As CSale
    '    Dim objsale As New CSale
    '    Try
    '        With objsale
    '            .PartyID = intParty
    '            .PromoterID = CounterNo
    '            .SaleDate = Me.dtpSaleDate.Value
    '            .SaleType = saleType
    '            .Amount = DSale.GetCounterAmount(CounterNo)
    '            .Discount = 0   'THIS DISCOUNT IS DISCOUNT ON BILL
    '            .PaidAmt = .Amount
    '            .TotalTax = 0
    '            .GrossAmt = .Amount + .TotalTax
    '        End With
    '        Return objsale
    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
    '        Return Nothing
    '    End Try
    'End Function

    Private Function ItemsSelected(ByVal SelctedOrActive As Char) As Boolean
        'IF SELECTED ROWS ARE BLANK THEN REMOVE SELECTION OF THAT ROW/ROWS
        'AFTER THIS IF SELECTED ROWS ARE >0 THEN RETRURN TRUE
        'ELSE RETURN FALSE
        Try

        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "ItemsSelected")
        End Try
    End Function

    'Private Sub CalculateReturnAmt() 'Written By:-  Kumar (20071017):----    'CALCULATE THE RETURN AMOUNT
    '    'Dim dblPaidAmount As Double = 0
    '    'Dim dblGrossAmt As Double = 0
    '    'Try
    '    '    If Me.txtOtherCharges.Text <> "" Then
    '    '        dblPaidAmount = Convert.ToDouble(Me.txtOtherCharges.Text.ToString())
    '    '    Else : dblPaidAmount = "0.00"
    '    '        Me.txtOtherCharges.Text = "0.00"
    '    '    End If
    '    '    dblGrossAmt = IIf(Me.txtTotalAmt.Text <> "", Convert.ToDouble(Me.txtTotalAmt.Text.ToString()), "0.00")
    '    '    Me.txtGrossAmt.Text = IIf(dblPaidAmount <= dblGrossAmt, "0.00", Format((dblPaidAmount - dblGrossAmt), "0.00"))
    '    'Catch ex As Exception
    '    '    BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "CalculateReturnAmt")
    '    'End Try
    'End Sub

    Private Sub CalculateAmt()
        Dim intCount As Integer
        Try
            With fgItems
                TotAmount = 0.0


                For intCount = 0 To .Rows.Count - 1
                    If IsNothing(.Item(ItemGridColumns.AMOUNT, intCount).Value) OrElse Trim(.Item(ItemGridColumns.AMOUNT, intCount).Value) = "" Then Exit For
                    TotAmount = TotAmount + .Item(ItemGridColumns.AMOUNT, intCount).Value
                Next
                txtTotalAmt.Text = Format(TotAmount, "0.00")

                CalculateTotalOtherCharges()
                '//txtOtherCharges.Text = Format(TotAmount, "0.00")
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "CalculateAmt")
        End Try
    End Sub
#End Region '"ONLY FOR SALE FORM"


    Enum ItemGridColumns
        ITEMID = 0
        CODE = 1
        ITEMNAME = 2

        CLRCODE = 3
        CLRDESC = 4

        PACK = 5
        GODOWN = 6
        SCHEMEID = 7
        'DISC = 8
        QTY = 9
        PRICE = 10
        AMOUNT = 11
        STATUS = 12

        EXPIRY = 13


        CLRID = 14

        CONVERSIONUNIT = 15

        GODOWNID = 16

        STOCKDETAILS = 17
        TAX = 18
        PACKID = 19
        PACKUPDATEID = 20

    End Enum
#Region "COMMON SEARCH"


    Private Sub txtPartyCode_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPartyCode.Enter, txtPartyName.Enter, txtItemCode.Enter, txtItemName.Enter, txtPromoterCode.Enter, txtPromoterName.Enter, txtCLRCODE.Enter, txtCLRNAME.Enter, txtSiteCode.Enter, txtSiteName.Enter, txtGoDown.Enter
        If BtLoading Then Exit Sub
        If sender.Text.ToString = String.Empty Then
            sender.BackColor = Color.LightBlue
            SearchParty_Promoter_Site(sender)
        End If
    End Sub

    'Private Sub txtPartyCode_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSiteName.Enter, txtSiteCode.Enter, txtPromoterName.Enter, txtPromoterCode.Enter, txtPartyName.Enter, txtPartyCode.Enter, txtItemName.Enter, txtItemCode.Enter, txtGoDown.Enter, txtCLRNAME.Enter, txtCLRCODE.Enter ' Handles txtPartyCode.Enter, txtPartyName.Enter, txtItemCode.Enter, txtItemName.Enter, txtPromoterCode.Enter, txtPromoterName.Enter, txtCLRCODE.Enter, txtCLRNAME.Enter, txtSiteCode.Enter, txtSiteName.Enter, txtGoDown.Enter
    '    If BtLoading Then Exit Sub
    '    If sender.Text.ToString = String.Empty Then
    '        sender.BackColor = Color.LightBlue
    '        SearchParty_Promoter_Site(sender)
    '    End If
    'End Sub
    Private Sub txtCLRCODE_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtPartyCode.KeyDown, txtPartyName.KeyDown, txtItemCode.KeyDown, txtItemName.KeyDown, txtPromoterCode.KeyDown, txtPromoterName.KeyDown, txtCLRCODE.KeyDown, txtCLRNAME.KeyDown, txtSiteCode.KeyDown, txtSiteName.KeyDown, txtGoDown.KeyDown
        If (cmbPack.Name <> sender.Name) AndAlso e.KeyCode = Keys.Space Then
            e.SuppressKeyPress = True
            SearchParty_Promoter_Site(sender)
        ElseIf e.KeyCode = Keys.Enter Then
            SendKeys.Send("{Tab}")
        ElseIf e.KeyCode = Keys.Tab Then
        ElseIf (cmbPack.Name <> sender.Name) Then
            e.SuppressKeyPress = True
        End If
    End Sub

    Private Function GetSearchQuery(ByVal Sender As Object, ByRef strSearchString As String) As String

        Select Case Sender.Name
            Case txtPartyCode.Name, txtPartyName.Name
                strSearchString = "PARTY "
                Return "SELECT P.Id,P.PartyCode AS CODE ,P.PartyName  AS NAME, P.Address +', PIN:' + CONVERT(VARCHAR (6),P.PinCode) +', ' + C.CityName  AS PartyAddrs FROM [NGSPaintsDB].[dbo].Party P INNER JOIN City	C ON (P.CityID= C.ID) WHERE P.IsDeleted=0"
            Case txtPromoterCode.Name, txtPromoterName.Name
                strSearchString = "PROMOTER "
                Return "SELECT P.Id,P.PromoterCode AS CODE ,P.PromoterName AS NAME FROM [NGSPaintsDB].[dbo].promoter P WHERE P.IsDeleted=0"
            Case txtSiteCode.Name, txtSiteName.Name
                strSearchString = "SITE "
                Return " SELECT [Id],[SiteCode]AS CODE ,[SiteName] AS NAME  FROM [NGSPaintsDB].[dbo].[Site] WHERE [IsDeleted]=0"
                'Case txtPrice.Name 'PRICE LIST
                'CmbPriceList.Focus()    Return "SELECT [ID],[PRICELISTCODE]AS CODE ,[PRICELISTNAME] AS NAME  FROM [NGSPAINTSDB].[DBO].[PRICELIST] WHERE [ISDELETED]=0"
            Case txtItemCode.Name, txtItemName.Name
                strSearchString = "PRODUCT "
                Return "SELECT P.[Id] AS ItemID,P.[ProductCode] AS Code,P.[ProductName] AS Name " & _
                         " FROM [NGSPaintsDB].[dbo].Product P  ORDER BY NAME"
            Case txtCLRCODE.Name, txtCLRNAME.Name
                If IntItem = 0 Then
                    Return ""
                End If
                strSearchString = "COLOR "
                Return "SELECT DISTINCT C.[Id],C.[ColorCode] AS CODE ,C.[ColorDescription] AS NAME  FROM [Color] AS C  INNER JOIN  PackingUpdateDetail  D ON (D.ColorID=C.ID) INNER JOIN  PackingUpdate P ON(P.ID=D.PackingUpdateId) WHERE C.[IsDeleted]=0 AND P.ProductID=" & IntItem.ToString
            Case txtGoDown.Name
                If IntItem = 0 OrElse intColor = 0 OrElse intPack = 0 Then
                    Return ""
                End If
                strSearchString = "GODOWN "
                'Return "SELECT C.[Id],C.[GoDownCode] AS CODE ,C.[GodownName] AS NAME FROM [GoDown] C  INNER JOIN PackingUpdateDetail D ON (D.GoDownID=C.ID AND D.ColorID=" & intColor & ") INNER JOIN  PackingUpdate P ON(P.ID=D.PackingUpdateId) INNER JOIN Packing K ON (D.PackingID=K.ID AND K.ID=" & intPack & ") WHERE C.[IsDeleted]=0 AND P.ProductID=" & IntItem
                'Return "SELECT C.[Id],C.[GoDownCode] AS CODE ,C.[GodownName] AS NAME ,Stock FROM [GoDown] C  INNER JOIN PackingUpdateDetail D ON (D.GoDownID=C.ID AND D.ColorID=" & intColor & " )  INNER JOIN  PackingUpdate P ON(P.ID=D.PackingUpdateId AND P.ProductID=" & IntItem & ") INNER JOIN PackingSize K ON (D.PackSizeID=K.ID  AND  K.ID=" & intPack & ") "
                Return "SELECT DISTINCT (C.[Id]),C.[GoDownCode] AS CODE ,C.[GodownName] AS NAME ,Stock FROM PackingUpdateDetail D INNER JOIN [GoDown] C ON (D.GoDownID=C.ID AND D.ColorID=" & intColor & ")  INNER JOIN  PackingUpdate P ON(P.ID=D.PackingUpdateId AND P.ProductID=" & IntItem & ")"
            Case cmbPack.Name
                If IntItem = 0 OrElse intColor = 0 Then
                    Return ""
                End If
                strSearchString = "PACK "
                'Return "SELECT  DISTINCT C.ID,PackingCode AS CODE ,PackingDescription AS NAME FROM Packing C INNER JOIN PackingUpdateDetail  D ON (D.PackingID=C.ID AND D.ColorID=" & intColor & ") INNER JOIN  PackingUpdate P ON(P.ID=D.PackingUpdateId) WHERE C.[IsDeleted]=0 AND P.ProductID=" & IntItem
                'Return "SELECT DISTINCT C.ID, S.PackSize + ' ' + S.PackingDescription  FROM Packing C  INNER JOIN  PackingSize S ON(S.ID =C.PackingSizeId)INNER JOIN PackingUpdateDetail  D ON (D.PackingID=C.ID) INNER JOIN  PackingUpdate P ON(P.ID=D.PackingUpdateId) WHERE C.[IsDeleted]=0 AND P.ProductID=" & IntItem.ToString
                'Return "SELECT DISTINCT C.ID, S.PackSize + ' ' + S.PackingDescription AS CODE,D.ID AS PackingIpdateID FROM Packing C  INNER JOIN  PackingSize S ON(S.ID =C.PackingSizeId)INNER JOIN PackingUpdateDetail  D ON (D.PackingID=C.ID) INNER JOIN  PackingUpdate P ON(P.ID=D.PackingUpdateId) WHERE C.[IsDeleted]=0 AND P.ProductID=" & IntItem.ToString
                Return "SELECT DISTINCT D.ID, S.PackSize + ' ' + S.PackingDescription AS CODE FROM  PackingSize S INNER JOIN PackingUpdateDetail  D ON (D.PackSizeID=S.ID) INNER JOIN  PackingUpdate P ON(P.ID=D.PackingUpdateId) WHERE S.[IsDeleted]=0 AND P.ProductID=" & IntItem.ToString & "  AND ColorID=" & intColor.ToString
            Case Else
                Return ""
        End Select
    End Function

    Private Sub SearchParty_Promoter_Site(ByVal sender As Object)
        Try
            Dim TxtSearch As TextBox = sender

            Dim frmListProducts As New frmProducts
            With frmListProducts

                .Left = fgItems.Right - .Width - 5
                .Top = fgItems.Top + 25
                .intSelectedItem = 0
                Dim strSearch As String = ""
                .StrSearchQuery = GetSearchQuery(TxtSearch, strSearch)
                If .StrSearchQuery = String.Empty Then Exit Sub
                .strSearchByCode = strSearch & IIf(sender.Name.ToString.ToUpper.Contains("CODE"), "CODE:", "NAME:")

                .txtProduct.Text = TxtSearch.Text
                .ShowDialog()
                'intSelectedProduct = frmListProducts.intSelectedItem
            End With


            If frmListProducts.intSelectedItem > 0 Then
                With frmListProducts.fgProducts
                    If .CurrentRow.Index >= 0 Then
                        Select Case TxtSearch.Name
                            Case txtPartyCode.Name, txtPartyName.Name
                                intParty = .Item(0, .CurrentRow.Index).Value
                                txtPartyCode.Text = .Item(1, .CurrentRow.Index).Value
                                txtPartyName.Text = .Item(2, .CurrentRow.Index).Value
                                rTxtAddress.Text = .Item(3, .CurrentRow.Index).Value
                                sender.BackColor = Color.White
                                txtPromoterCode.Focus()
                            Case txtPromoterCode.Name, txtPromoterName.Name
                                intPromoter = .Item(0, .CurrentRow.Index).Value
                                txtPromoterCode.Text = .Item(1, .CurrentRow.Index).Value
                                txtPromoterName.Text = .Item(2, .CurrentRow.Index).Value
                                sender.BackColor = Color.White
                                txtSiteCode.Focus()
                            Case txtSiteCode.Name, txtSiteName.Name
                                intSite = .Item(0, .CurrentRow.Index).Value
                                txtSiteCode.Text = .Item(1, .CurrentRow.Index).Value
                                txtSiteName.Text = .Item(2, .CurrentRow.Index).Value
                                sender.BackColor = Color.White
                                CmbPriceList.Focus()
                            Case txtItemCode.Name, txtItemName.Name
                                subPriClearItemDtls()
                                IntItem = .Item(0, .CurrentRow.Index).Value
                                txtItemCode.Text = .Item(1, .CurrentRow.Index).Value
                                txtItemName.Text = .Item(2, .CurrentRow.Index).Value
                                'subPriUpdatePack()
                                'sender.BackColor = Color.White
                                txtCLRCODE.Focus()
                            Case txtCLRCODE.Name, txtCLRNAME.Name
                                intColor = .Item(0, .CurrentRow.Index).Value
                                txtCLRCODE.Text = .Item(1, .CurrentRow.Index).Value
                                txtCLRNAME.Text = .Item(2, .CurrentRow.Index).Value
                                subPriUpdatePack()
                                sender.BackColor = Color.White
                                cmbPack.Focus()
                                'cmbPack.DroppedDown = True
                            Case txtGoDown.Name ''
                                intGodownID = .Item(0, .CurrentRow.Index).Value
                                txtGoDown.Text = .Item(2, .CurrentRow.Index).Value
                                sender.BackColor = Color.White
                                txtQty.Focus()
                            Case cmbPack.Name '
                                intPack = .Item(0, .CurrentRow.Index).Value
                                ' cmbPack.Text = .Item(1, .CurrentRow.Index).Value
                                SubPriGetPrice()
                                sender.BackColor = Color.White
                                txtGoDown.Focus()
                            Case Else
                                Exit Sub
                        End Select
                    End If
                End With
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "showProductList")
        Finally
            sender.BackColor = Color.White
        End Try
    End Sub
#End Region
    Private Sub subPriUpdatePack()
        BtLoading = True
        Dim strPackQury As String = GetSearchQuery(cmbPack, "")
        Dim dtbpack As DataTable = DbHelper.ExecuteDataTable(strPackQury)
        Dim pk(0) As System.Data.DataColumn
        pk(0) = dtbpack.Columns(0)
        dtbpack.PrimaryKey = pk
        cmbPack.DataSource = dtbpack
        cmbPack.ValueMember = "ID"
        cmbPack.DisplayMember = "CODE"
        BtLoading = False

    End Sub
    Private Sub cmbPack_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbPack.SelectedValueChanged

    End Sub
    Private Sub cmbPack_SelectionChangeCommitted(sender As Object, e As System.EventArgs) Handles cmbPack.SelectionChangeCommitted
        If BtLoading Then Exit Sub
        intPack = cmbPack.SelectedValue
        '

        intPackingUpdateID = intPack
        SubPriGetPrice()
        txtGoDown.Focus()
    End Sub
    Private Sub txtPrice_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtPrice.KeyDown
        e.SuppressKeyPress = True  'INSTEAD OF DISABLE CONTROL(IT AFFECTS THE UI) MANUAY KEYS ARE SUPPRESSED SO USER CANT EDIT  THE VALUE. TEXT BOX LOOKS ENABLE BUT NOT
    End Sub

    Private Sub txtQty_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtQty.KeyDown
        If BCommon.ValidateText(txtQty.Text.Trim, e.KeyCode, "NUM", False) = False Then
            e.SuppressKeyPress = True
        End If
    End Sub

    Private Sub txtPrice_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPrice.TextChanged, txtQty.TextChanged
        SubPriCalcItemAmnt()
    End Sub

    Private Sub SubPriCalcItemAmnt()
        Try
            If Me.txtPrice.Text.ToString() <> String.Empty AndAlso Me.txtQty.Text.ToString() <> String.Empty Then
                txtItemAmount.Text = Convert.ToDouble(Me.txtPrice.Text.ToString()) * Convert.ToDouble(Me.txtQty.Text.ToString())
            Else
                txtItemAmount.Text = 0
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
            txtItemAmount.Text = 0
        End Try
    End Sub
    Private Sub txtAmount_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtItemAmount.KeyDown
        If e.KeyCode = Keys.Enter Then
            SetItemToGrid()
        End If
        e.SuppressKeyPress = True
    End Sub
    Private Sub SetItemToGrid()
        Try
            If funPriIsValidItem() Then
                subPriSetItemInGrid()
                subPriClearItemDtls()
                txtItemCode.Focus()
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub
    Private Sub txtAmount_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtItemAmount.LostFocus
        SetItemToGrid()
    End Sub
    Private Function funPriIsValidItem() As Boolean
        Try
            Dim BlnResult As Boolean = True
            If IntItem = 0 Then
                txtItemCode.Focus()
                BlnResult = False
            ElseIf intColor = 0 Then
                txtCLRCODE.Focus()
                BlnResult = False
                'ElseIf intGodownID = 0 Then
                '    txtGoDown.Focus()
                '    BlnResult = False
            ElseIf txtQty.Text = String.Empty OrElse System.Convert.ToInt64(txtQty.Text) <= 0 Then
                txtQty.Focus()
                BlnResult = False
            ElseIf txtPrice.Text.Trim = String.Empty OrElse System.Convert.ToDouble(txtPrice.Text) <= 0 Then
                txtPrice.Focus()
                Return False
            End If
            Return BlnResult
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
            Return False
        End Try
    End Function

    Private Sub subPriSetItemInGrid()
        Try
            Dim intCurrentRow As Integer

            With fgItems
                If .Rows.Count <= intCurrentRow Then
                    .Rows.Add(10)
                End If
                If intLastRow > 0 Then
                    intCurrentRow = intLastRow
                Else
                    Dim intCunt As Integer
                    For intCunt = 0 To .Rows.Count - 1
                        If IsNothing(.Item(ItemGridColumns.ITEMID, intCunt).Value) OrElse .Item(ItemGridColumns.ITEMID, intCunt).Value.ToString() = String.Empty Then
                            Exit For
                        End If
                    Next
                    intCurrentRow = intCunt
                End If
                .Item(ItemGridColumns.CODE, intCurrentRow).Value = txtItemCode.Text

                .Item(ItemGridColumns.ITEMNAME, intCurrentRow).Value = txtItemName.Text
                .Item(ItemGridColumns.CLRCODE, intCurrentRow).Value = txtCLRCODE.Text
                .Item(ItemGridColumns.CLRDESC, intCurrentRow).Value = txtCLRNAME.Text
                .Item(ItemGridColumns.PACK, intCurrentRow).Value = cmbPack.Text
                .Item(ItemGridColumns.GODOWN, intCurrentRow).Value = txtGoDown.Text
                .Item(ItemGridColumns.PRICE, intCurrentRow).Value = txtPrice.Text
                .Item(ItemGridColumns.QTY, intCurrentRow).Value = txtQty.Text
                .Item(ItemGridColumns.AMOUNT, intCurrentRow).Value = txtItemAmount.Text

                .Item(ItemGridColumns.ITEMID, intCurrentRow).Value = IntItem
                .Item(ItemGridColumns.GODOWNID, intCurrentRow).Value = intGodownID
                .Item(ItemGridColumns.CLRID, intCurrentRow).Value = intColor
                .Item(ItemGridColumns.PACKID, intCurrentRow).Value = intPack
                .Item(ItemGridColumns.PACKUPDATEID, intCurrentRow).Value = intPackingUpdateID
                '.Item(ItemGridColumns.GODOW, intCurrentRow).Value = intGodownID
                intCurrentRow = 0
                CalculateAmt()
                CalculateTotalOtherCharges()

            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        Finally
            intLastRow = 0
        End Try
    End Sub
    Sub subPriClearItemDtls()
        Try
            txtItemCode.Text = String.Empty
            txtItemName.Text = String.Empty
            txtCLRCODE.Text = String.Empty
            txtCLRNAME.Text = String.Empty
            cmbPack.SelectedIndex = -1
            txtGoDown.Text = String.Empty
            txtQty.Text = String.Empty
            txtItemAmount.Text = String.Empty
            txtPrice.Text = String.Empty


            intPack = 0
            intColor = 0
            IntItem = 0
            intGodownID = 0
            intPackingUpdateID = 0

        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub
    Private Sub SubPriGetPrice()
        Try
            txtPrice.Text = DbHelper.ExecuteScalar("SELECT Rate FROM PriceListDetail WHERE PriceListID=" & intPriceList & " AND ProductID=" & IntItem & " AND PAckingID=" & intPack)
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub

    Private Sub CmbPriceList_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles CmbPriceList.KeyDown
        If e.KeyCode = Keys.Enter Then
            SendKeys.Send("{Tab}")
        End If
    End Sub

    Private Sub CmbPriceList_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CmbPriceList.SelectedValueChanged
        If BtLoading Then Exit Sub
        If Not CmbPriceList.SelectedValue = Nothing Then
            intPriceList = CmbPriceList.SelectedValue

        End If
    End Sub

    Private Sub fgItems_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles fgItems.DoubleClick
        With fgItems
            If Not IsNothing(.Item(ItemGridColumns.AMOUNT, .CurrentRow.Index).Value) Then
                intLastRow = .CurrentRow.Index
                Dim intCurrentRow As Integer = intLastRow
                IntItem = .Item(ItemGridColumns.ITEMID, intCurrentRow).Value
                intPack = .Item(ItemGridColumns.PACKID, intCurrentRow).Value
                txtQty.Text = .Item(ItemGridColumns.QTY, intCurrentRow).Value
                intColor = .Item(ItemGridColumns.CLRID, intCurrentRow).Value
                intPackingUpdateID = intPack
                txtItemCode.Text = .Item(ItemGridColumns.CODE, intCurrentRow).Value
                txtItemName.Text = .Item(ItemGridColumns.ITEMNAME, intCurrentRow).Value
                txtCLRCODE.Text = .Item(ItemGridColumns.CLRCODE, intCurrentRow).Value
                txtCLRNAME.Text = .Item(ItemGridColumns.CLRDESC, intCurrentRow).Value
                txtGoDown.Text = .Item(ItemGridColumns.GODOWN, intCurrentRow).Value
                txtPrice.Text = .Item(ItemGridColumns.PRICE, intCurrentRow).Value
                txtItemAmount.Text = .Item(ItemGridColumns.AMOUNT, intCurrentRow).Value

                cmbPack.SelectedValue = intPack
                subPriUpdatePack()
                'cmbPack.Text = .Item(ItemGridColumns.PACK, intCurrentRow).Value
            End If
        End With
    End Sub

    Private Sub fgItems_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles fgItems.KeyDown
        If e.KeyCode = Keys.Enter Then
            fgItems_DoubleClick(Nothing, Nothing)
        ElseIf e.KeyCode = Keys.Delete Then
            If MessageBox.Show("Do you want to delete record?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = vbYes Then
                SubPriDeleteRecord()
            End If
        End If
    End Sub
    Private Sub SubPriDeleteRecord()
        Try
            With fgItems
                If Not IsNothing(.Item(ItemGridColumns.AMOUNT, .CurrentRow.Index).Value) Then
                    .Rows.Remove(.CurrentRow)
                End If
            End With

        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        Finally
            CalculateAmt()
            CalculateTotalOtherCharges()
        End Try
    End Sub

    Private Sub SetOtherCharges(Optional ByVal boolLoadforBill As Boolean = False)

        Try
            'SET GRID
            With dgOtherCharges
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .AllowUserToOrderColumns = False
                .AllowUserToResizeRows = False
                .RowHeadersVisible = False
                Dim DtbOtherCharges As New DataTable

                If boolLoadforBill = True Then
                    DtbOtherCharges = DSale.GetSaleBillOtherCharges(intVoucherID)
                Else
                    DtbOtherCharges = DSale.GetOtherCharges()

                End If
                Dim pk(0) As System.Data.DataColumn
                pk(0) = DtbOtherCharges.Columns(0)
                DtbOtherCharges.PrimaryKey = pk
                .DataSource = DtbOtherCharges
                .Columns(0).Visible = False  'ID
                .Columns(4).Visible = False  'ISTAXABLE
                .Columns(1).ReadOnly = True 'NAME
                .Columns(3).ReadOnly = True 'Amount
            End With

        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub

    Private Sub CalculateTotalOtherCharges()
        Dim dblOtherCharges As Double = 0.0
        Dim strValue As String
        Try
            With dgOtherCharges
                For intRow As Int16 = 0 To .Rows.Count - 1
                    strValue = .Item(2, intRow).Value
                    .Item(3, intRow).Value = GetOtherCharge(strValue)
                    dblOtherCharges = dblOtherCharges + System.Convert.ToDouble(.Item(3, intRow).Value)
                Next
                txtOtherCharges.Text = dblOtherCharges
                txtGrossAmt.Text = System.Convert.ToDouble(txtTotalAmt.Text) + dblOtherCharges
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "")
        End Try
    End Sub

    Private Sub dgOtherCharges_CellEndEdit(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgOtherCharges.CellEndEdit
        CalculateTotalOtherCharges()
    End Sub
    Private Function GetOtherCharge(strValue As String) As Double
        If strValue.Contains("%") Then
            strValue = strValue.Replace("%", "")
            Dim DblValue As Double = Convert.ToDouble(strValue)
            Dim dblTotalAmt As Double = Convert.ToDouble(txtTotalAmt.Text)
            Return (DblValue * dblTotalAmt) / 100
        Else
            Return Convert.ToDouble(strValue)
        End If
    End Function
    Private Sub dgOtherCharges_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles dgOtherCharges.KeyDown
        If BCommon.ValidateText(txtOtherCharges.Text, e.KeyCode, "NUM", True) = False Then
            If e.KeyCode <> Keys.A% Then
                e.SuppressKeyPress = True
            End If
        End If
    End Sub
#Region "SEARCH SALE "

    Private Sub txtSearch_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtSearch.KeyDown
        If e.KeyCode = Keys.Enter Then
            SearchVoucher()
            Exit Sub
        End If
        If BCommon.ValidateText(txtQty.Text.Trim, e.KeyCode, "NUM", False) = False Then
            e.SuppressKeyPress = True
        End If
    End Sub

    Private Sub SearchVoucher()
        Try
            If txtSearch.Text.Trim() = String.Empty OrElse System.Convert.ToInt16(txtSearch.Text) = 0 Then
                MessageBox.Show("Please Enter the ID", "NiranjanPaints", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Else
                Dim intSeqVoucherID As Int64 = System.Convert.ToInt16(txtSearch.Text)

                intVoucherID = DbHelper.ExecuteScalar("SELECT SaleID FROM tSale WHERE SeqSaleID =" & intSeqVoucherID.ToString() & " AND SaleType=" & System.Convert.ToInt16(saleType).ToString())
                If (intVoucherID > 0) Then
                    subPriFillDetails()
                Else
                    MessageBox.Show("Record not found!!!", "NiranjanPaints", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End If
            End If

        Catch ex As Exception

        End Try
    End Sub
    Private Sub subPriFillDetails()
        Dim intTempVoucherID As Integer = intVoucherID
        Call ClearData()
        intVoucherID = intTempVoucherID
        Dim DtbSale As DataTable = DSale.GetSaleBill(intVoucherID)
        Dim dtbSaleItems As DataTable = DSale.GetSaleBillItems(intVoucherID)
        'Dim dtbOtherChrgs As DataTable = 


        With DtbSale.Rows(0)
            'S.SeqSaleID,S.PartyCode AS PartyID,P.PartyCode,P.PartyName, S.SaleDate,S.PromoterID,R.PromoterName,R.PromoterCode,S.SiteID,S.Amount,S.OtherCharges,S.TotalTaxes,
            'S.Discount, S.GrossAmount, S.ShipingAddress, S.SaleType, PriceListID, T.SiteName, T.SiteCode
            saleType = .Item("SaleType")
            Select Case saleType
                Case DGeneral.DocTypes.APPROVAL
                    BtnApprove_Click(Nothing, Nothing)
                Case DGeneral.DocTypes.CASH_MEMO
                    BtnCash_Click(Nothing, Nothing)
                Case DGeneral.DocTypes.CHALLAN
                    BtnChallan_Click(Nothing, Nothing)
                Case DGeneral.DocTypes.INVOICE
                    BtnInvoice_Click(Nothing, Nothing)
                Case DGeneral.DocTypes.QUOTATION
                    BtnQuote_Click(Nothing, Nothing)
            End Select

            txtVoucher.Text = .Item("SeqSaleID")
            txtPartyCode.Text = .Item("PartyCode")
            txtPartyName.Text = .Item("PartyName")
            txtPromoterCode.Text = .Item("PromoterCode")
            txtPromoterName.Text = .Item("PromoterName")
            txtTotalAmt.Text = .Item("Amount")
            txtGrossAmt.Text = .Item("GrossAmount")
            txtOtherCharges.Text = .Item("OtherCharges")
            txtSiteCode.Text = .Item("SiteCode")
            txtSiteName.Text = .Item("SiteName")
            rTxtAddress.Text = .Item("ShipingAddress")
            intParty = .Item("PartyID")
            intPromoter = .Item("PromoterID")
            intSite = .Item("SiteID")
            intPriceList = .Item("PriceListID")
            CmbPriceList.SelectedValue = intPriceList
            '.Text = .Item("")

            '''''-------------------------Item Details
        End With
        ''''''Fill Sale Details
        'S.ItemID,P.ProductName,P.ProductCode,S.CLRcode AS CLRID,C.ColorCode,C.ColorDescription, S.PackUpdateID,S.SalePrice,S.Qty,S.Amount,S.SchemeDiscount SELECT S.ItemID,
        'P.ProductName,P.ProductCode,S.CLRcode AS CLRID,C.ColorCode,C.ColorDescription, S.PackUpdateID,S.SalePrice,S.Qty,S.Amount,S.SchemeDiscount, PCK 
        Dim intCurrentRow As Integer = 0
        For Each SaleITem As DataRow In dtbSaleItems.Rows

            If fgItems.Rows.Count <= intCurrentRow Then
                fgItems.Rows.Add(10)
            End If
            fgItems.Item(ItemGridColumns.CODE, intCurrentRow).Value = SaleITem.Item("ProductCode") 'txtItemCode.Text

            fgItems.Item(ItemGridColumns.ITEMNAME, intCurrentRow).Value = SaleITem.Item("ProductName") ' txtItemName.Text
            fgItems.Item(ItemGridColumns.CLRCODE, intCurrentRow).Value = SaleITem.Item("ColorCode") 'txtCLRCODE.Text
            fgItems.Item(ItemGridColumns.CLRDESC, intCurrentRow).Value = SaleITem.Item("ColorDescription") 'txtCLRNAME.Text
            fgItems.Item(ItemGridColumns.PACK, intCurrentRow).Value = SaleITem.Item("PCK") 'cmbPack.Text
            fgItems.Item(ItemGridColumns.GODOWN, intCurrentRow).Value = SaleITem.Item("GodownName") 'txtGoDown.Text
            fgItems.Item(ItemGridColumns.PRICE, intCurrentRow).Value = SaleITem.Item("SalePrice") 'txtPrice.Text
            fgItems.Item(ItemGridColumns.QTY, intCurrentRow).Value = SaleITem.Item("Qty") 'txtQty.Text
            fgItems.Item(ItemGridColumns.AMOUNT, intCurrentRow).Value = SaleITem.Item("Amount") 'txtItemAmount.Text

            fgItems.Item(ItemGridColumns.ITEMID, intCurrentRow).Value = SaleITem.Item("ItemID") 'IntItem
            fgItems.Item(ItemGridColumns.GODOWNID, intCurrentRow).Value = SaleITem.Item("GodownId") 'intGodownID
            fgItems.Item(ItemGridColumns.CLRID, intCurrentRow).Value = SaleITem.Item("CLRID") 'intColor
            fgItems.Item(ItemGridColumns.PACKID, intCurrentRow).Value = SaleITem.Item("PackUpdateID") 'intPack
            fgItems.Item(ItemGridColumns.PACKUPDATEID, intCurrentRow).Value = SaleITem.Item("PackUpdateID") 'intPackingUpdateID
            intCurrentRow += 1
        Next
        'intCurrentRow = 0
        ''''''Fill Other Charges
        SetOtherCharges(True)
    End Sub

#End Region
#Region "Summary"
    Private Sub SubPriUpdateAndDisplaySumary()

    End Sub
#End Region
End Class